<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      <el-breadcrumb-item>用户菜单</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <div>
        <el-row :gutter="20">
          <el-col :span="8">
            <!-- 搜索框 -->
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getAccountList">
              <el-button slot="append" icon="el-icon-search" @click="getAccountList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="getRoleList;addDialogVisible = true;">添加用户</el-button>
          </el-col>
        </el-row>
        <el-table
          :data="accountList"
          border
          stripe
        >
          <el-table-column type="index"></el-table-column>
          <el-table-column
            prop="email"
            label="用户名"
          >
          </el-table-column>
          <el-table-column
            prop="roleId"
            label="角色"
          >
            <template slot-scope="scope">
              {{ getRoleName(scope.row.roleId) }}
            </template>
          </el-table-column>
          <el-table-column
            label="账号状态"
            prop="status"
          >
            <template slot-scope="scope">
              {{ getStatus(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="账户信息" placement="top" :enterable="false">
                <el-button type="primary" icon="el-icon-edit" size="mini"
                           @click="getUserInfo(scope.row.id);updateDialogVisible = true;updateDisabled = true"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除账户" placement="top" :enterable="false">
                <el-button type="danger" icon="el-icon-delete" size="mini"
                           @click="deleteAccount(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="管理账户" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini"
                           @click="manageDialogVisible = true;updateManageInfo(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 15]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <el-dialog
          title="添加账户"
          :visible.sync="addDialogVisible"
          width="50%">
          <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
            <el-form-item prop="email" label="用户名">
              <el-input v-model="addForm.email" clearable></el-input>
            </el-form-item>
            <el-form-item prop="password" label="账户密码">
              <el-input v-model="addForm.password" type="password" clearable></el-input>
            </el-form-item>
            <el-form-item prop="roleId" label="账户角色">
              <el-select v-model="addForm.roleId" placeholder="请选择账户角色">
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addAccount">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog
          title="修改账户信息"
          :visible.sync="updateDialogVisible"
          width="50%">
          <el-form ref="updateFormRef" :model="updateForm" :rules="updateFormRules" label-width="80px">
            <el-form-item prop="username" label="昵称">
              <el-input v-model="updateForm.username" clearable :disabled="updateDisabled"></el-input>
            </el-form-item>
            <el-form-item prop="personalBio" label="个性签名">
              <el-input v-model="updateForm.personalBio" clearable :disabled="updateDisabled"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="updateDialogVisible = false">取 消</el-button>
            <el-button @click="updateDisabled = !updateDisabled" type="info">
              {{ updateDisabled ? '开 启' : '关 闭' }} 修 改
            </el-button>
            <el-button type="primary" @click="updateUserInfo">确 定</el-button>
          </span>
        </el-dialog>
        <el-dialog
          title="管理账户"
          :visible.sync="manageDialogVisible"
          width="50%">
          <el-form ref="updateFormRef" label-width="80px">
            <el-form-item label="封禁账户">
              <el-switch
                v-model="banned"
                inactive-color="#13ce66"
                active-color="#ff4949"
                active-text="已封禁"
                inactive-text="未封禁"
                @change="modifyBanned"
              >
              </el-switch>
            </el-form-item>
            <el-form-item label="禁言账户">
              <el-switch
                v-model="muted"
                inactive-color="#13ce66"
                active-color="#ff4949"
                active-text="已禁言"
                inactive-text="未禁言"
                @change="modifyMuted"
              >
              </el-switch>
            </el-form-item>
            <el-form-item label="账户角色">
              <el-select v-model="updateRoleForm.roleId" placeholder="请选择账户角色">
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <el-button style="margin-left: 15px" type="warning" @click="updateRole">修改账户角色</el-button>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="manageDialogVisible = false">取 消</el-button>
          </span>
        </el-dialog>
      </div>
    </el-card>

  </div>
</template>

<script>
export default {
  data () {
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5
      },
      accountList: [],
      roleList: [],
      total: 0,
      addDialogVisible: false,
      updateDialogVisible: false,
      authorityDialogVisible: false,
      addForm: {
        email: '',
        password: '',
        roleId: 2,
        status: 'NORMAL'
      },
      addFormRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱或用户名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请填写密码',
            trigger: 'blur'
          }
        ],
        roleId: [
          {
            required: true,
            message: '请输入角色',
            trigger: 'blur'
          }
        ]
      },
      updateForm: {
        accountId: 0,
        username: '',
        personalBio: '',
        balance: 0
      },
      updateFormRules: {
        username: [
          {
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          }
        ],
        personalBio: [
          {
            required: true,
            message: '请输入账户个性签名',
            trigger: 'blur'
          }
        ]
      },
      updateDisabled: true,
      manageDialogVisible: false,
      updateRoleForm: {
        id: 0,
        roleId: 0
      },
      muteBanForm: {
        id: 0
      },
      banned: false,
      muted: false
    }
  },
  created () {
    this.getAccountList()
    this.getRoleList()
  },
  methods: {
    async getAccountList () {
      const { data: res } = await this.$http.get('/account', { params: this.queryInfo })
      if (res.code !== 200) {
        this.$message.error('获取用户列表失败')
        return
      }
      this.accountList = res.data.accounts.records
      this.total = res.data.accounts.total
    },
    async getRoleList () {
      const { data: res } = await this.$http.get('/role/all')
      if (res.code === 200) {
        this.roleList = res.data.roles
      } else {
        this.$message.error('请求角色列表失败')
      }
    },
    async getUserInfo (id) {
      const { data: res } = await this.$http.get('/info/id', { params: { id: id } })
      if (res.code === 200) {
        this.$message.success('获取用户信息成功')
        this.updateForm.accountId = res.data.userInfo.accountId
        this.updateForm.username = res.data.userInfo.username
        this.updateForm.personalBio = res.data.userInfo.personalBio
        this.updateForm.balance = res.data.userInfo.balance
      } else {
        this.$message.error('获取用户信息失败')
      }
    },
    async updateUserInfo () {
      this.$refs.updateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/info/id', this.updateForm)
        console.log(res)
        if (res.code === 200) {
          this.$message.success('更新账户信息成功')
          this.updateDialogVisible = false
        } else {
          this.$message.error('更新账户信息失败')
        }
      })
    },
    getStatus (status) {
      if (status === 'NORMAL') {
        return '正常'
      } else if (status === 'BANNED') {
        return '账号封禁'
      } else {
        return '被禁言状态'
      }
    },
    getRoleName (roleId) {
      for (const role of this.roleList) {
        if (role.id === roleId) {
          return role.roleName
        }
      }
    },
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getAccountList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getAccountList()
    },
    addAccount () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/account', this.addForm)
        console.log(res)
        if (res.code === 201) {
          this.$message.success(res.message)
          this.addDialogVisible = false
          await this.getAccountList()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    deleteAccount (accountId) {
      this.$confirm('此操作将永久删除该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('/account', { data: { id: accountId } })
        if (res.code === 200) {
          this.$message.success('删除用户成功')
          await this.getAccountList()
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    muteAccount () {
      this.$confirm('此操作将禁言该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.put('/account/mute', this.muteBanForm)
        if (res.code === 200) {
          this.$message.success('禁言账户成功')
          await this.getAccountList()
        } else {
          this.$message.error('禁言失败')
          this.muted = false
        }
      }).catch(() => {
        this.$message.info('已取消')
        this.muted = false
      })
    },
    rollbackMuted () {
      this.$confirm('此操作将取消禁言该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.put('/account/normal', this.muteBanForm)
        if (res.code === 200) {
          this.$message.success('取消禁言账户成功')
        } else {
          this.$message.error('取消禁言失败')
          this.muted = false
        }
      }).catch(() => {
        this.$message.info('已取消')
        this.muted = false
      })
    },
    banAccount () {
      this.$confirm('此操作将封禁该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.put('/account/ban', this.muteBanForm)
        if (res.code === 200) {
          this.$message.success('封禁账户成功')
          await this.getAccountList()
        } else {
          this.$message.error('封禁失败')
        }
      }).catch(() => {
        this.$message.info('已取消')
      })
    },
    rollbackBanned () {
      this.$confirm('此操作将取消封禁该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.put('/account/normal', this.muteBanForm)
        if (res.code === 200) {
          this.$message.success('取消封禁账户成功')
        } else {
          this.$message.error('取消封禁失败')
          this.banned = false
        }
      }).catch(() => {
        this.$message.info('已取消')
        this.banned = false
      })
    },
    updateManageInfo (info) {
      this.updateRoleForm.id = info.id
      this.updateRoleForm.roleId = info.roleId
      this.muteBanForm.id = info.id
      if (info.status === 'MUTED') {
        this.muted = true
      }
      if (info.status === 'BANNED') {
        this.banned = true
      }
    },
    modifyMuted () {
      if (this.muted === true) {
        this.muteAccount()
      } else {
        this.rollbackMuted()
      }
    },
    modifyBanned () {
      if (this.banned === true) {
        this.banAccount()
      } else {
        this.rollbackBanned()
      }
    },
    updateRole () {
      this.$confirm('此操作将修改该账户角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.put('/account/role', this.updateRoleForm)
        if (res.code === 200) {
          this.$message.success('修改账户角色成功')
          await this.getAccountList()
        } else {
          this.$message.error('修改账户角色失败')
        }
      }).catch(() => {
        this.$message.info('已取消')
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
